/*******************************************************************************
 * Copyright (c) 2014-7-22 @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a>.
 * All rights reserved.
 *
 * Contributors:
 *     <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> - initial API and implementation
 ******************************************************************************/
package com.foreveross.project.projectonline.config;

import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.handler.Handler;
import com.jfinal.kit.StrKit;

/**
 * <pre>
 * provide functions:
 * 1. Url Skip: put skip url to excludePaths
 * 2. Request attribute:
 * 3. fake static:
 * </pre>
 * @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> 
 * @since 2014-7-22
 */
public class CommonHandler extends Handler {

	public static final HashSet<String> excludePaths = new HashSet<String>();
	private Map<String, Object> applicationMap;

	public CommonHandler() {
		super();
		{
			excludePaths.add("/servlet/");
		}
	}

	public CommonHandler(Map<String, Object> applicationMap) {
		this();
		this.applicationMap = applicationMap;
	}

	public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
		for (String excludePath : excludePaths) {
			if (target.startsWith(excludePath)) {
				return;
			}
		}
		{
			if (target.startsWith("/pages")) {
				String[] includePathPrefix = new String[] { "/pages/201410/css/", "/pages/201410/images/",
						"/pages/201410/js/", "/pages/js", "/pages/css/", "/pages/img/" };
				boolean isIncludePath = false;
				for (String include : includePathPrefix) {
					if (target.startsWith(include)) {
						isIncludePath = true;
						break;
					}
				}
				if (!isIncludePath) {
					target = "/";
				}
			}
		}
		if (applicationMap != null && !applicationMap.isEmpty()) {
			for (Entry<String, Object> entry : applicationMap.entrySet()) {
				request.setAttribute(entry.getKey(), entry.getValue());
			}
		}
		{
			String serverContext = request.getHeader("server-context");
			if (StrKit.isBlank(serverContext)) {
				request.setAttribute("CPATH", request.getContextPath());
			} else {
				request.setAttribute("CPATH", serverContext + request.getContextPath());
			}
		}
		{//fake static
			int index = target.lastIndexOf(".html");
			if (index != -1) {
				target = target.substring(0, index);
			}
		}
		nextHandler.handle(target, request, response, isHandled);
	}
}